import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'

const TOKEN_NAME = 'token'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        let token = localStorage.getItem(TOKEN_NAME)
        if (token) {
            config.headers[TOKEN_NAME] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code === 2000) {
            return res
        }
        if (res.code === 4001) {
            ElMessageBox.alert('登录过期，请重新登录~', '提示', {
                type: 'warning',
                showClose: false,
                confirmButtonText: '确定'
            }).then(() => {
                localStorage.clear()
                window.location.reload()
            })
        } else {
            ElMessage({
                type: 'error',
                message: res.msg,
                duration: 4 * 1000
            })
        }
        return Promise.reject(new Error(res.msg || 'Error'))
    },
    error => {
        ElMessage({
            type: 'error',
            message: error.message || 'Error',
            duration: 4 * 1000
        })
    }
)

// 下载文件
service.download = (url, params, fileName, fileType) => {
    const loadingInstance = ElLoading.service({lock: true, text: '正在下载，请稍后…'})
    axios({
        url: process.env.VUE_APP_BASE_API + url,
        method: 'get',
        params: params,
        //headers: {[TOKEN_NAME]: localStorage.getItem(TOKEN_NAME)},
        responseType: 'blob'
    }).then(async response => {
        if (response.data.type === 'application/json') {
            const res = JSON.parse(await response.data.text())
            ElMessage.error(res.msg)
        } else {
            const blob = new Blob([response.data], {type: fileType})
            const url = window.URL.createObjectURL(blob)
            // 创建下载链接
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
        }
    }).catch(error => {
        console.log('下载失败:', error)
        ElMessage.error('下载失败，请稍后再试~')
    }).finally(() => {
        loadingInstance.close()
    })
}

// 下载excel
service.downloadExcel = (url, params, fileName) => {
    fileName = (fileName || 'excel') + '_' + new Date().getTime() + '.xls'
    service.download(url, params, fileName, 'application/vnd.ms-excel')
}

export default service
